package com.atguigu.flink0624.chapter11.function;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/20 10:29
 */
public class Flink01_Function_Scalar {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        Table table = tenv.fromValues("hello world", "hello atguigu", "hello");
        
        
        // 1. 在table api中使用
        // 1.1. 内联使用
        /*table
            .select($("f0"), call(MyUpperCase.class, $("f0")).as("u"))
            .execute()
            .print();*/
        // 1.2. 注册后使用
        /*tenv.createTemporaryFunction("my_upper", MyUpperCase.class);
        table
            .select($("f0"), call("my_upper", $("f0")).as("u"))
            .execute()
            .print();*/
        
        // 2. 在sql语句中使用
        tenv.createTemporaryFunction("my_upper", MyUpperCase.class);
        tenv
            .sqlQuery("select *, my_upper(f0) from " + table)
            .execute()
            .print();
        
    }
    
    public static class MyUpperCase extends ScalarFunction {
        public String eval(String s) {
            return s == null ? null : s.toUpperCase();
        }
    }
}
